from PyQt5.QtCore import QObject,QThread,pyqtSignal
from PyQt5.QtWidgets import QMainWindow, QMessageBox
import win32api,win32gui,win32con
import time

from package.Utils.Screen import screen   # 导入 screen 对象(python代码)
from package.Utils.log import logger,mylog  # 导入 logger 对象(python代码)
from package.Utils.Remind import set_alarm  # 导入 set_alarm 函数(python代码)

#QT线程类
class MyThread(QThread):

    hwnd_received = pyqtSignal(int)

    def __init__(self,parent=None):
        super(MyThread, self).__init__(parent)  # 初始化父类

        self.thread = QThread()
        self.moveToThread(self.thread)
        if mylog.log_enabled is True:
            logger.info('MyThread线程创建成功')
        # self.hwnd_received.connect(self.Update_MousePosition_information)

        self.active  = False  # 线程运行状态控制

    def Start(self):
        self.active = True
        self.thread.started.connect(self.run)
        self.thread.start()
        if mylog.log_enabled is True:
            logger.info('线程启动')

    def run(self):
        """核心监听逻辑"""
        while self.active:
            # 检测鼠标左键是否被按下（GetAsyncKeyState返回值为负数表示按下状态）
            if win32api.GetAsyncKeyState(win32con.VK_LBUTTON) < 0:
                self._process_click()
                break
            time.sleep(0.01)   # 降低CPU占用率

    def stop(self):
        """安全停止线程"""
        self.thread.requestInterruption()  # 请求中断
        self.thread.quit()
        self.thread.wait()
        self.active  = False
        from package.Utils.MainWindow import mybasicsetwin,mywinutils  # 导入 mybasicsetwin 对象(python代码)
        mybasicsetwin.lineEdit_hwnd.setText(str(mywinutils.hwnd))  # 显示窗口句柄
        if mylog.log_enabled is True:
            logger.info(f"获取成功：窗口句柄：{mywinutils.hwnd}")
            logger.info('线程停止')

    def _process_click(self):
        """处理点击事件并获取窗口句柄"""
        # 等待按键释放，避免重复触发
        while win32api.GetAsyncKeyState(win32con.VK_LBUTTON) < 0:
            time.sleep(0.01)

        # 获取点击坐标及窗口句柄
        x, y = win32api.GetCursorPos()
        hwnd = win32gui.WindowFromPoint((x, y))
        top_hwnd = win32gui.GetAncestor(hwnd, win32con.GA_ROOT)  # 获取顶层窗口

        # 发送信号并终止线程
        self.hwnd_received.emit(top_hwnd)
        from package.Utils.MainWindow import mybasicsetwin,mywinutils  # 导入 mybasicsetwin 对象(python代码)
        mywinutils.hwnd = top_hwnd  # 保存窗口句柄

        self.stop()

class MyTimeThread(QThread):

    hwnd_received = pyqtSignal(int)

    def __init__(self,parent=None):
        super(MyTimeThread, self).__init__(parent)  # 初始化父类

        self.thread = QThread()
        self.moveToThread(self.thread)
        if mylog.log_enabled is True:
            logger.info('MyTimeThread线程创建成功')
        # self.hwnd_received.connect(self.Update_MousePosition_information)

        self.active  = False  # 线程运行状态控制

    def Start(self):
        self.active = True
        self.thread.started.connect(self.run)
        self.thread.start()
        if mylog.log_enabled is True:
            logger.info('线程启动')

    def run(self):
        """判断时间是否到达"""
        from package.Utils.MainWindow import mywinutils  # 导入 mywinutils 对象(python代码)
        while True:
            set_alarm(mywinutils.Time_H,mywinutils.Time_M,mywinutils.time_msg)
            time.sleep(1)   # 降低CPU占用率
    def stop(self):
        """安全停止线程"""
        self.thread.requestInterruption()  # 请求中断
        self.thread.quit()
        self.thread.wait()
        self.active  = False
        from package.Utils.MainWindow import mybasicsetwin,mywinutils  # 导入 mybasicsetwin 对象(python代码)
        mybasicsetwin.lineEdit_hwnd.setText(str(mywinutils.hwnd))  # 显示窗口句柄
        if mylog.log_enabled is True:
            logger.info(f"获取成功：窗口句柄：{mywinutils.hwnd}")
            logger.info('线程停止')

mythread = MyThread()  # 实例化 MyThread 类

mytimethread = MyTimeThread()  # 实例化 MyTimeThread 类